package com.nwcl.ysx.controller;

import com.nwcl.basic.bo.GoodsBO;
import com.nwcl.basic.bo.OrdersBO;
import com.nwcl.basic.bo.OrdersDetailBO;
import com.nwcl.basic.bo.UserIntegralFlowBO;
import com.nwcl.basic.service.*;
import com.nwcl.common.constant.Constant;
import com.nwcl.common.result.Page;
import com.nwcl.common.result.Result;
import com.nwcl.common.utils.DateUtil;
import com.nwcl.common.utils.SessionUtil;
import com.nwcl.ysx.request.GoodsCashRequest;
import com.nwcl.ysx.request.OrdersPageRequest;
import com.nwcl.ysx.vo.CashVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/*
 * @Description:商品积分兑换
 * @Author liguiqin
 * @Date 2023/5/29 13:52
 * @param: null
 * @return
 * @UpdateDate 2023/5/29 13:52
 **/
@RestController
@RequestMapping("/api/ysx/cash")
public class ApiCashController {
    @Autowired
    private GoodsSpaceService goodsSpaceService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrdersDetailService ordersDetailService;
    @Autowired
    private SessionUtil sessionUtil;
    @Autowired
    private UserIntegralService userIntegralService;
    @Autowired
    private UserIntegralFlowService userIntegralFlowService;

    /*
     * @Description:  商品兑换
     * @Author liguiqin
     * @Date 2023/5/26 14:12
     * @param:
     * @return com.nwcl.common.result.Result
     * @UpdateDate 2023/5/26 14:12
     **/
    @PostMapping("/cashGoods")
    public Result cashGoods(@RequestBody GoodsCashRequest param, HttpServletRequest request) {
        Integer userId = sessionUtil.getUserId(request);
        Result rs = param.check();
        if (rs != null) {
            return rs;
        }
        int num = 1;//兑换数量
        //1.查询商品信息是否存在
        GoodsBO goodsBO = goodsService.getById(param.getGoodsId());
        if (goodsBO == null) {
            return Result.fail("商品不存在");
        }
        //2.查询用户积分
        BigDecimal userIntegral = userIntegralService.getIntegralByUser(userId);
        //3.判断用户积分是否充足,库存是否充足,并扣减商品库存
        goodsSpaceService.deduction(goodsBO, userId, userIntegral, num);
        //4.生成订单
        OrdersBO ordersBO = getOrdersBO(userId, num, goodsBO);
        Integer orderId = ordersService.save(ordersBO);
        //5.生成订单详情
        OrdersDetailBO ordersDetailBO = getOrdersDetailBO(num, goodsBO, orderId);
        ordersDetailService.save(ordersDetailBO);
        //6.扣减用户积分,并生成积分流水记录
        userIntegralService.deduction(userId, goodsBO.getIntegral(), orderId);
        return Result.success();
    }




    /*
     * @Description:  我的兑换记录
     * @Author liguiqin
     * @Date 2023/5/29 14:01
     * @param: param
     * @param: request
     * @return com.nwcl.common.result.Result
     * @UpdateDate 2023/5/29 14:01
     **/
    @GetMapping("/list")
    public Result list(@RequestBody OrdersPageRequest param, HttpServletRequest request) {
        Page<CashVO> resultPage = new Page<>();
        param.setUserId(sessionUtil.getUserId(request));//
        param.setSourceType(Constant.OrderSourceType.integral);
        param.setType(Constant.OrderType.integral);
        Page<OrdersBO> page = ordersService.page(param);
        List<CashVO> voList = warpList(page.getList());
        resultPage = new Page<>(page.getPageNum(), page.getPageSize(), page.getTotal(), voList);
        return Result.success(resultPage);
    }

    /*
     * @Description: 封装返回数据
     * @Author liguiqin
     * @Date 2023/5/29 14:21
     * @param: list
     * @return java.util.List<com.nwcl.ysx.vo.CashVO>
     * @UpdateDate 2023/5/29 14:21
     **/
    private List<CashVO> warpList(List<OrdersBO> list) {
        List<CashVO> voList = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            return voList;
        }
        List<Integer> orderIds = new ArrayList<>();
        for (OrdersBO ordersBO : list) {
            orderIds.add(ordersBO.getId());
        }
        Map<Integer, List<OrdersDetailBO>> ordersDetailMap = ordersDetailService.mapByOrderIds(orderIds);
        Map<Integer, UserIntegralFlowBO> userIntegralFlowMap = userIntegralFlowService.mapByOrderIds(orderIds);
        for (OrdersBO ordersBO : list) {
            UserIntegralFlowBO flowBO=userIntegralFlowMap.get(ordersBO.getId());
            CashVO vo = new CashVO();
            vo.setOrderCode(ordersBO.getOrderCode());
            vo.setId(ordersBO.getId());
            vo.setPrice(ordersBO.getPrice());
            vo.setRealPrice(ordersBO.getRealPrice());
            vo.setOrderCode(ordersBO.getOrderCode());
            vo.setIntegral(flowBO!=null?flowBO.getIntegral():new BigDecimal(0));
            vo.setCreateTime(DateUtil.formatDateTime(ordersBO.getCreateTime()));
            List<OrdersDetailBO> detailBOS = ordersDetailMap.get(ordersBO.getId());
            if (!CollectionUtils.isEmpty(detailBOS)) {
                OrdersDetailBO detailBO = detailBOS.get(0);
                vo.setGoodsName(detailBO.getGoodsName());
                vo.setGoodsImg(detailBO.getGoodsImg());
                vo.setGoodsNum(detailBO.getNum());
            }
            voList.add(vo);
        }
        return voList;
    }

    private OrdersBO getOrdersBO(Integer userId, int num, GoodsBO goodsBO) {
        OrdersBO ordersBO = new OrdersBO();
        ordersBO.setType(Constant.OrderType.integral);
        ordersBO.setOrderCode(ordersService.generateOrderCode(ordersBO.getType()));
        ordersBO.setUserId(userId);
        ordersBO.setPrice(goodsBO.getPrice());
        ordersBO.setRemark(goodsBO.getIntegral() + "积分兑换" + num + "个[" + goodsBO.getName() + "]");
        ordersBO.setSourceType(Constant.OrderSourceType.integral);
        ordersBO.setStatus(Constant.OrderStatus.pay);
        ordersBO.setPrice(goodsBO.getPrice().multiply(new BigDecimal(num)));
        ordersBO.setRealPrice(new BigDecimal(0));
        ordersBO.setCreateUserId(userId);
        ordersBO.setCreateTime(new Date());
        ordersBO.setUpdateTime(new Date());
        ordersBO.setIsValid(Constant.isValid.valid);
        return ordersBO;
    }

    private OrdersDetailBO getOrdersDetailBO(int num, GoodsBO goodsBO, Integer orderId) {
        OrdersDetailBO ordersDetailBO = new OrdersDetailBO();
        ordersDetailBO.setOrderId(orderId);
        ordersDetailBO.setGoodsImg(goodsBO.getDefaultImg());
        ordersDetailBO.setGoodsId(goodsBO.getId());
        ordersDetailBO.setGoodsName(goodsBO.getName());
        ordersDetailBO.setPrice(goodsBO.getPrice());
        ordersDetailBO.setNum(new BigDecimal(num));
        ordersDetailBO.setCreateTime(new Date());
        ordersDetailBO.setUpdateTime(new Date());
        ordersDetailBO.setIsValid(Constant.isValid.valid);
        return ordersDetailBO;
    }
}
